package com.pig4cloud.pig.module.service.vip.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.platform.PlatformPay;
import com.pig4cloud.pig.module.api.entity.vip.VipOrder;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.vip.VipOrderMapper;
import com.pig4cloud.pig.module.service.base.IParameterService;
import com.pig4cloud.pig.module.service.platform.IPlatformPayService;
import com.pig4cloud.pig.module.service.vip.IVipOrderService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;


/**
 * 套餐活动支付订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-20
 */
@Service
public class VipOrderServiceImpl extends ServiceImpl<VipOrderMapper, VipOrder> implements IVipOrderService {

	@Resource
	private VipOrderMapper vipOrderMapper;
	@Resource
	private IParameterService parameterService;
	@Resource
	private IPlatformPayService platformPayService;
	@Resource
	private IWxUserService wxUserService;
	@Resource
	private IWxPayTransactionService wxPayTransactionService;

	@Value("${web.appid}")
	private String appid;
	@Value("${web.appidMp}")
	private String appidMp;
	@Value("${web.secret}")
	private String secret;
	@Value("${web.mch_id}")
	private String mch_id;
	@Value("${web.api_key}")
	private String api_key;
	@Value("${web.keyPath}")
	private String keyPath;//微信支付的回调地址
	@Value("${web.wx_refund_notify_url}")
	private String wx_refund_notify_url;//微信支付的回调地址

	@Override
	@Transactional
	public int refundOrder(VipOrder vipOrder) {
		int ret = 0;
		try{
			PlatformPay platformPay = platformPayService.getDefaultAccount();
			VipOrder orders = vipOrderMapper.selectById(vipOrder.getId());
			if(orders != null){
				String out_refund_no = OrderUtil.getOrderNoByTimespan();
				orders.setRefundOutTradeNo(out_refund_no);
				boolean bl = false;
				if(orders.getStatus() == 2){
					if(orders.getPayType() == 0) {
						WxAppPay wxAppPay = new WxAppPay(wx_refund_notify_url, secret, appid, mch_id, api_key);
						Map<String, String> retRequest = wxAppPay.refundPayAPI(orders.getOutTradeNo(),orders.getPayPrice(),orders.getPayPrice(),orders.getRefundOutTradeNo(),keyPath);
						if(retRequest.containsKey("return_code")){
							String result_code = retRequest.get("result_code");
							String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
//							map.put("result_code",result_code);
//							map.put("err_code_des",err_code_des);
							if(result_code.equals("SUCCESS")){
								orders.setStatus(6);//同意退款
								orders.setRefundStatus(1);
							}else{
								orders.setStatus(9);//退款失败
							}
							ret = vipOrderMapper.updateById(orders);
							if(ret <= 0){
								throw new TransactionalException("productOrderInfoMapper insert error");
							}
						}
					}else{
						out_refund_no =  platformPay.getSysCode() + OrderUtil.getOrderNoByTimespan();
						orders.setRefundOutTradeNo(out_refund_no);
						//String out_trade_no, BigDecimal refund_money, String out_refund_no,PlatformPay platformPay
						String retRequest = platformPayService.refundOrder(orders.getOutTradeNo(), orders.getPayPrice(),orders.getRefundOutTradeNo(),platformPay);
						System.out.println("会员退款申请响应: " + retRequest);
						JSONObject jsonObject = JSONUtil.parseObj(retRequest);
						if(jsonObject!=null){
							String errCode = jsonObject.getStr("errCode");
							String errMsg = jsonObject.getStr("errMsg");
							String refundStatus = jsonObject.getStr("refundStatus");
							if(errCode.equals("SUCCESS") && refundStatus.equals("SUCCESS")){
								orders.setStatus(6);//同意退款
								orders.setRefundStatus(1);
							}else{
								orders.setStatus(9);//退款失败
							}
							ret = vipOrderMapper.updateById(orders);
							if(ret <= 0){
								throw new TransactionalException("productOrderInfoMapper insert error");
							}
						}
					}
				}
			}
			ret = 1;
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("productOrderInfoMapper insert error");
		}
		return ret;
	}

	@Override
	@Transactional
	public int queryRefundOrder(VipOrder vipOrder) {
		int ret = 0;
		try{
			PlatformPay platformPay = platformPayService.getDefaultAccount();
			//收费的充电,并且是微信支付  才发起退款
			String retRequest = "";
			if(vipOrder.getPayType() == 0) {
				WxAppPay wxAppPay = new WxAppPay(wx_refund_notify_url, secret, appid, mch_id, api_key);
				retRequest = wxAppPay.refundQueryAPI(vipOrder.getOutTradeNo());
				System.out.println("微信支付退款响应: " + retRequest);
			} else {
				//String out_trade_no, PlatformPay platformPay
				retRequest = platformPayService.refundOrderQuery(vipOrder.getRefundOutTradeNo(), platformPay);
				System.out.println("农商行退款响应: " + retRequest);
			}

			JSONObject jsonObject = JSONUtil.parseObj(retRequest);
			if (jsonObject != null) {
				String code = "";
				String msg = "";
				String transaction_id = "",trade_no = "";
				String refundTime = "";
				double refund_fee = 0d;
				boolean bl = false;
				if(vipOrder.getPayType() == 0) {
					code = jsonObject.containsKey("code") ? jsonObject.getStr("code") : "";
					msg = jsonObject.containsKey("msg") ? jsonObject.getStr("msg") : "";
					if (code.equals("SUCCESS")) {
						bl = true;
						transaction_id = jsonObject.containsKey("transaction_id") ? jsonObject.getStr("transaction_id") : "";
						refundTime = jsonObject.containsKey("refund_success_time") ? jsonObject.getStr("refund_success_time") : "";
						refund_fee = jsonObject.containsKey("refund_fee") ? jsonObject.getDouble("refund_fee") : 0d;
						refund_fee = refund_fee / 100;
						trade_no = transaction_id;
					}
				}else{
					//{"payTime":"2022-10-13 08:35:17","connectSys":"UNIONPAY","errMsg":"查询成功","merName":"跃豆智慧生活科技（山东）有限公司",
					// "mid":"8983711651302D6","refundStatus":"FAIL","settleDate":"2022-10-13","tid":"8699CXK6","targetMid":"534866521",
					// "cardAttr":"BALANCE","targetStatus":"SUCCESS","seqId":"30138123195N","merOrderId":"32WT00000001665562150772","targetSys":"WXPay",
					// "bankInfo":"OTHERS","delegatedFlag":"N","settleRefId":"30128664338N","refundOrderId":"32WT10001665621317132","totalAmount":98,
					// "chnlCost":"758","responseTimestamp":"2022-10-13 12:35:24","errCode":"SUCCESS","status":"TRADE_CLOSED"}
					code = jsonObject.getStr("errCode");
					msg = jsonObject.getStr("errMsg");
					if (code.equals("SUCCESS")) {
						bl = true;
						transaction_id = jsonObject.containsKey("targetOrderId") ? jsonObject.getStr("targetOrderId") : "";
//						refundTime = jsonObject.containsKey("refundPayTime") ? jsonObject.getStr("refundPayTime") : "";
						refund_fee = jsonObject.containsKey("totalAmount") ? jsonObject.getDouble("totalAmount") : 0d;
						trade_no = transaction_id;
						refund_fee = refund_fee / 100;
					}
				}

				if (bl) {
					//订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 订单已完成 4 -  订单取消  5 - 已发起退款  6 - 同意退款  7 - 拒绝退款  8 - 退款完成 9 - 退款失败
					vipOrder.setStatus(8);
//					0 未退款 1 申请中 2 已退款  3 退款失败
					vipOrder.setRefundStatus(2);
					vipOrder.setRefundPrice(new BigDecimal(refund_fee));
					vipOrder.setRefundOutTradeNo(transaction_id);
					vipOrder.setRefundReasonTime(new Date());

					String out_trade_no = vipOrder.getOutTradeNo();
					// 添加 微信支付的 动账记录
					QueryWrapper<WxPayTransaction> qwTrans = new QueryWrapper<>();
					qwTrans.and(wrapper->{
						wrapper.eq("transaction_no",vipOrder.getOutTradeNo())
							.or().eq("transaction_id",vipOrder.getOutTradeNo())
							.or().eq("out_trade_no",vipOrder.getOutTradeNo());
					});
					qwTrans.eq("fee_type","vip_refund");
					qwTrans.last("limit 1");
					WxUser user = wxUserService.findById(vipOrder.getUserId());

					WxPayTransaction transaction = wxPayTransactionService.getOne(qwTrans);
					if(transaction == null){
						transaction = new WxPayTransaction();
						transaction.setEstateId(vipOrder.getEstateId());
						transaction.setEstateName(vipOrder.getEstateName());
						transaction.setTransactionNo(out_trade_no);
						transaction.setPayType(vipOrder.getPayType());// 0 -微信支付
						transaction.setTransactionId(trade_no);
						transaction.setUserId(user.getId());
						transaction.setFeeType("vip_refund");
						transaction.setTotalMoney(new BigDecimal(refund_fee ));
						transaction.setOutTradeNo(out_trade_no);
						if(StrUtil.isNotEmpty(user.getNickName())){
							transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
						}
						transaction.setCreateTime(new Date());
						transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
						transaction.setRemark("会员充值退款");
						transaction.setPayPlatformId(vipOrder.getPayPlatformId());
						wxPayTransactionService.save(transaction);
					}else{
						transaction.setTotalMoney(new BigDecimal(refund_fee));
						wxPayTransactionService.updateById(transaction);
					}

					ret = vipOrderMapper.updateById(vipOrder);
					if(ret <= 0){
						throw new TransactionalException("chargerOrderMapper updateById error");
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return ret;
	}
}
